<template>
    <div class="page-container">
        <!-- 页面标题 -->
        <div class="page-title">
            <div class="title-container">
                <span>用水单耗统计</span>
                <div class="title-actions">
                    <el-button type="primary" icon="Setting" class="unit-manage-btn"
                        @click="handleUnitManage">单耗单位管理</el-button>
                    <el-button type="primary" @click="handleExport">
                        <template #icon>
                            <SvgIcon icon="download" />
                        </template>
                        导出
                    </el-button>
                </div>

            </div>

        </div>
        <el-card>
            <!-- 头部区域 -->
            <div class="header-container">
                <div class="current-table">
                    当前表格：
                    <el-dropdown trigger="click" @command="handleTableChange">
                        <span class="el-dropdown-link">
                            {{ currentTableName }}
                            <el-icon class="el-icon--right"><arrow-down /></el-icon>
                        </span>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item v-for="table in tableList" :key="table.id" :command="table.id">{{
                                    table.name }}</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </div>
                <div class="header-actions">
                    <el-button icon="Plus" link @click="handleCreateTable">
                        新建表格
                    </el-button>
                    <el-button icon="Edit" link @click="handleEditTableName">
                        修改表格标题
                    </el-button>
                </div>
                <div class="view-switch">
                    <el-radio-group v-model="currentView" size="small">
                        <el-radio-button value="table" label="table">表格</el-radio-button>
                        <el-radio-button va label="chart">图表</el-radio-button>
                    </el-radio-group>
                </div>
            </div>

            <!-- 表格视图 -->
            <div v-show="currentView === 'table'">
                <vxe-table :export-config="exportConfig" ref="tableRef" :cell-config="cellConfig"
                    :row-drag-config="rowDragConfig" border :data="filteredTableData"
                    :column-config="{ resizable: true }" :row-config="rowConfig">
                    <vxe-column drag-sort width="150" align="center" field="unitType" title="单耗单位">
                        <template #default="{ row }">
                            <template v-if="row.isEditing">
                                <vxe-select style="width: 100px;margin-left: 10px;" v-model="row.unitType"
                                    @change="handleUnitTypeChange(row)">
                                    <vxe-option v-for="unit in unitList" :key="unit.id" :value="unit.symbol"
                                        :label="unit.symbol" />
                                </vxe-select>
                            </template>
                            <template v-else>
                                {{ row.unitType }}
                            </template>
                        </template>
                    </vxe-column>
                    <vxe-column field="area" title="区域" align="center">
                        <template #default="{ row }">
                            <template v-if="row.isEditing">
                                <vxe-select v-model="row.area" @change="handleCellChange">
                                    <vxe-option value="全部" label="全部" />
                                    <vxe-option v-for="area in areaStore.areas" :value="area.name"
                                        :label="area.name"></vxe-option>
                                </vxe-select>
                            </template>
                            <template v-else>
                                {{ row.area }}
                            </template>
                        </template>
                    </vxe-column>
                    <vxe-column field="periodUnit" title="周期单位" align="center">
                        <template #default="{ row }">
                            <template v-if="row.isEditing">
                                <vxe-select v-model="row.periodUnit" @change="handlePeriodUnitChange(row)">
                                    <vxe-option value="a" label="a (年)"></vxe-option>
                                    <vxe-option value="m" label="m (月)"></vxe-option>
                                    <vxe-option value="d" label="d (日)"></vxe-option>
                                    <vxe-option value="s" label="s (季)"></vxe-option>
                                </vxe-select>
                            </template>
                            <template v-else>
                                {{ row.periodUnit }}
                            </template>
                        </template>
                    </vxe-column>
                    <vxe-column field="period" width="140" title="周期" align="center">
                        <template #default="{ row }">
                            <template v-if="row.isEditing">
                                <el-date-picker style="width: 120px;" v-model="row.period"
                                    :type="getPeriodPickerType(row.periodUnit)"
                                    :placeholder="getPeriodPlaceholder(row.periodUnit)"
                                    :format="getPeriodFormat(row.periodUnit)"
                                    :value-format="getPeriodValueFormat(row.periodUnit)"
                                    @change="handlePeriodChange(row)" />
                            </template>
                            <template v-else>
                                {{ formatPeriodDisplay(row.period, row.periodUnit) }}
                            </template>
                        </template>
                    </vxe-column>
                    <vxe-column field="waterUnit" title="水量单位" align="center">
                        <template #default="{ row }">
                            {{ row.waterUnit }}
                        </template>
                    </vxe-column>
                    <vxe-column field="periodWaterConsumption" title="周期用水量" align="center">
                        <template #default="{ row }">
                            <template v-if="row.isEditing">
                                <vxe-input v-model="row.periodWaterConsumption" type="number"
                                    @change="handleCellChange"></vxe-input>
                            </template>
                            <template v-else>
                                <span @click="handleWaterConsumptionClick(row)"
                                    :class="{ 'empty-value': !row.periodWaterConsumption || row.periodWaterConsumption === '无数据，点击手动录入' || row.periodWaterConsumption === '点击录入' }">
                                    {{ row.periodWaterConsumption || '点击录入' }}
                                </span>
                            </template>
                        </template>
                    </vxe-column>
                    <vxe-column field="allocUnit" title="分摊单位" align="center">
                        <template #default="{ row }">
                            {{ row.allocUnit }}
                        </template>
                    </vxe-column>
                    <vxe-column field="allocAmount" title="分摊数量" align="center">
                        <template #default="{ row }">
                            <template v-if="row.isEditing">
                                <vxe-input v-model="row.allocAmount" type="number"
                                    @change="handleCellChange"></vxe-input>
                            </template>
                            <template v-else>
                                <span @click="handleAllocAmountClick(row)"
                                    :class="{ 'empty-value': !row.allocAmount || row.allocAmount === '点击录入' }">
                                    {{ row.allocAmount || '点击录入' }}
                                </span>
                            </template>
                        </template>
                    </vxe-column>
                    <vxe-column field="unitConsumption" title="单耗" align="center">
                        <template #default="{ row }">
                            {{ row.unitConsumption || '自动生成' }}
                        </template>
                    </vxe-column>
                    <vxe-column field="commonValue" title="通用值" align="center">
                        <template #default="{ row }">
                            <template v-if="row.isEditing">
                                <vxe-input v-model="row.commonValue" type="number"
                                    @change="handleCellChange"></vxe-input>
                            </template>
                            <template v-else>
                                {{ row.commonValue }}
                            </template>
                        </template>
                    </vxe-column>
                    <vxe-column field="advancedValue" title="先进值" align="center">
                        <template #default="{ row }">
                            <template v-if="row.isEditing">
                                <vxe-input v-model="row.advancedValue" type="number"
                                    @change="handleCellChange"></vxe-input>
                            </template>
                            <template v-else>
                                {{ row.advancedValue }}
                            </template>
                        </template>
                    </vxe-column>
                    <vxe-column title="操作" fixed="right" align="center">
                        <template #default="{ row }">
                            <div class="operation-buttons">
                                <template v-if="row.isEditing">
                                    <el-button type="success" size="small" circle :icon="Check"
                                        @click="saveRow(row)"></el-button>
                                    <el-button type="info" size="small" circle :icon="Close"
                                        @click="cancelEdit(row)"></el-button>
                                </template>
                                <template v-else>
                                    <el-button type="primary" size="small" circle :icon="Edit"
                                        @click="editRow(row)"></el-button>
                                    <el-button type="danger" size="small" circle :icon="Delete"
                                        @click="deleteRow(row)"></el-button>
                                </template>
                            </div>
                        </template>
                    </vxe-column>
                </vxe-table>

                <!-- 底部工具栏 -->
                <div class="table-footer">
                    <el-button type="primary" :icon="Plus" @click="addNewRecord">添加一条新记录</el-button>
                </div>
            </div>

            <!-- 图表视图 -->
            <div v-if="currentView === 'chart'" class="chart-container">
                <ConsumptionChart :chart-data="chartDataForD3" :title="currentTableName" />
            </div>
        </el-card>

        <!-- 编辑表格名称对话框 -->
        <el-dialog v-model="editNameDialogVisible" title="修改表格标题" width="30%">
            <el-form :model="editNameForm">
                <el-form-item label="表格名称" label-width="80px">
                    <el-input v-model="editNameForm.name" autocomplete="off" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editNameDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveTableName">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 新建表格对话框 -->
        <el-dialog v-model="createTableDialogVisible" title="新建表格" width="30%">
            <el-form :model="createTableForm">
                <el-form-item label="表格名称" label-width="80px">
                    <el-input v-model="createTableForm.name" autocomplete="off" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="createTableDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="createNewTable">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 单耗单位管理对话框 -->
        <el-dialog v-model="unitManageDialogVisible" title="单耗单位管理" width="50%">
            <div class="unit-manage-container">
                <div class="unit-manage-header">
                    <el-button type="primary" @click="openUnitSelector">
                        <el-icon>
                            <plus />
                        </el-icon> 新增单位
                    </el-button>
                </div>
                <el-table :data="unitList" border style="width: 100%">
                    <el-table-column prop="symbol" label="单位" />
                    <el-table-column label="操作" width="180">
                        <template #default="scope">
                            <el-button type="danger" size="small" @click="deleteUnit(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-dialog>

        <el-dialog v-model="unitSelectorDialogVisible" title="新增单位" width="70%" top="5vh" append-to-body>
            <UnitSelector @confirm="handleUnitConfirm" @cancel="handleUnitCancel" />
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { Edit, Delete, Plus, ArrowDown, Check, Close } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import UnitSelector from './components/UnitSelector.vue'
import ConsumptionChart from './components/ConsumptionChart.vue'
import { useAreaStore } from '@/stores/area'
import SvgIcon from '@/components/Icon/SvgIcon.vue'
const areaStore = useAreaStore()
const tableRef = ref(null)
const exportConfig = {
    filename: '用水单耗统计',
    type: 'xlsx',
    original: false,
    useStyle: true,
}
// 表格列表
const tableList = ref([
    { id: '1', name: '历年人均用水' },
    { id: '2', name: '年度能耗指标' },
    { id: '3', name: '月度用水量' }
])

// 当前表格
const currentTableName = ref('历年人均用水')
const currentTableId = ref('1')

// 编辑表格名称相关
const editNameDialogVisible = ref(false)
const editNameForm = reactive({
    name: ''
})

// 新建表格相关
const createTableDialogVisible = ref(false)
const createTableForm = reactive({
    name: ''
})

const rowDragConfig = reactive({
    icon: 'vxe-icon-sort',
    trigger: 'cell',
})

const cellConfig = reactive({
    height: 50
})
const rowConfig = reactive({
    isHover: true,
    drag: true
})

// 单耗单位管理相关
const unitManageDialogVisible = ref(false)
const unitSelectorDialogVisible = ref(false)
const unitList = ref([
    { id: '1', symbol: 'm³/(人·a)' },
    { id: '2', symbol: 'm³/(万元·a)' },
    { id: '3', symbol: 'm³/t' },
    { id: '4', symbol: 'm³/万粒' }
])

// 表格数据
const tableData = ref([
    {
        tableId: '1',
        unitType: 'm³/(人·a)',
        area: '全部',
        periodUnit: 'a',
        period: '2022',
        waterUnit: 'm³',
        periodWaterConsumption: '453783.16',
        allocUnit: '人·a',
        allocAmount: '5937',
        unitConsumption: '76.43',
        commonValue: '85',
        advancedValue: '45',
        isEditing: false,
        originalData: null
    },
    {
        tableId: '1',
        unitType: 'm³/(人·a)',
        area: '全部',
        periodUnit: 'a',
        period: '2023',
        waterUnit: 'm³',
        periodWaterConsumption: '479625.74',
        allocUnit: '人·a',
        allocAmount: '6038',
        unitConsumption: '79.51',
        commonValue: '85',
        advancedValue: '45',
        isEditing: false,
        originalData: null
    },
    {
        tableId: '1',
        unitType: 'm³/(人·a)',
        area: '全部',
        periodUnit: 'a',
        period: '2021',
        waterUnit: 'm³',
        periodWaterConsumption: '无数据，点击手动录入',
        allocUnit: '人·a',
        allocAmount: '点击录入',
        unitConsumption: '',
        commonValue: '85',
        advancedValue: '45',
        isEditing: false,
        originalData: null
    },
    {
        tableId: '2',
        unitType: 'm³/(万元·a)',
        area: '全部',
        periodUnit: 'a',
        period: '2023',
        waterUnit: 'm³',
        periodWaterConsumption: '479625.74',
        allocUnit: '万元·a',
        allocAmount: '8562',
        unitConsumption: '56.02',
        commonValue: '60',
        advancedValue: '40',
        isEditing: false,
        originalData: null
    },
    {
        tableId: '3',
        unitType: 'm³/(人·m)',
        area: '全部',
        periodUnit: 'm',
        period: '2023-01',
        waterUnit: 'm³',
        periodWaterConsumption: '39968.81',
        allocUnit: '人·m',
        allocAmount: '6038',
        unitConsumption: '6.62',
        commonValue: '7.5',
        advancedValue: '4',
        isEditing: false,
        originalData: null
    }
])

// 当前显示的表格数据
const filteredTableData = computed(() => {
    return tableData.value.filter(item => item.tableId === currentTableId.value);
})



// 周期用水量单元格点击
const handleWaterConsumptionClick = (row) => {
    if (!row.isEditing && (!row.periodWaterConsumption ||
        row.periodWaterConsumption === '无数据，点击手动录入' ||
        row.periodWaterConsumption === '点击录入')) {
        editRow(row)
    }
}

// 分摊数量单元格点击
const handleAllocAmountClick = (row) => {
    if (!row.isEditing && (!row.allocAmount || row.allocAmount === '点击录入')) {
        editRow(row)
    }
}

// 单耗单位管理
const handleUnitManage = () => {
    unitManageDialogVisible.value = true
}

// 打开单位选择器
const openUnitSelector = () => {
    unitSelectorDialogVisible.value = true
}

// 接收单位选择器的确认
const handleUnitConfirm = (unit) => {
    // 检查单位是否已存在
    const exists = unitList.value.some(item => item.symbol === unit);
    if (exists) {
        ElMessage.warning(`单位 "${unit}" 已存在`);
        return;
    }

    // 添加新单位
    const newId = String(unitList.value.length + 1);
    unitList.value.push({
        id: newId,
        symbol: unit
    });

    ElMessage.success('单位添加成功');
    unitSelectorDialogVisible.value = false;
}

// 取消单位选择
const handleUnitCancel = () => {
    unitSelectorDialogVisible.value = false;
}

// 切换表格
const handleTableChange = (tableId) => {
    const selectedTable = tableList.value.find(table => table.id === tableId)
    if (selectedTable) {
        currentTableId.value = tableId
        currentTableName.value = selectedTable.name
        ElMessage.success(`已切换到表格：${selectedTable.name}`)
    }
}

// 单元格变更处理
const handleCellChange = (val, row) => {
    console.log('单元格数据变更:', val, row)
}

// 修改表格名称
const handleEditTableName = () => {
    editNameForm.name = currentTableName.value
    editNameDialogVisible.value = true
}

// 保存表格名称
const saveTableName = () => {
    if (!editNameForm.name.trim()) {
        ElMessage.warning('表格名称不能为空')
        return
    }

    const tableIndex = tableList.value.findIndex(table => table.id === currentTableId.value)
    if (tableIndex !== -1) {
        tableList.value[tableIndex].name = editNameForm.name
        currentTableName.value = editNameForm.name
        ElMessage.success('表格名称修改成功')
        editNameDialogVisible.value = false
    }
}

// 处理创建表格
const handleCreateTable = () => {
    createTableForm.name = ''
    createTableDialogVisible.value = true
}

// 创建新表格
const createNewTable = () => {
    if (!createTableForm.name.trim()) {
        ElMessage.warning('表格名称不能为空')
        return
    }

    const newId = String(tableList.value.length + 1)
    tableList.value.push({
        id: newId,
        name: createTableForm.name
    })

    // 自动切换到新表格
    currentTableId.value = newId
    currentTableName.value = createTableForm.name

    // 清空当前表格数据，实际应用中这里可能需要初始化新表格的结构
    // 注意：这里不需要清空tableData，因为我们现在使用filteredTableData来显示当前表格的数据

    ElMessage.success('新表格创建成功')
    createTableDialogVisible.value = false
}

// 添加新记录
const addNewRecord = () => {
    const defaultUnitType = unitList.value.length > 0 ? unitList.value[0].symbol : 'm³/(人·a)';

    // 从单耗单位中提取水量单位
    const waterUnit = extractWaterUnitFromUnitType(defaultUnitType);

    const newRecord = {
        tableId: currentTableId.value, // 关联到当前表格
        unitType: defaultUnitType,
        area: '全部',
        periodUnit: 'a',
        period: '',
        waterUnit: waterUnit, // 使用提取的水量单位
        periodWaterConsumption: '',
        allocUnit: extractAllocUnitFromUnitType(defaultUnitType), // 自动设置分摊单位
        allocAmount: '',
        unitConsumption: '自动生成',
        commonValue: '',
        advancedValue: '',
        isEditing: true, // 新记录默认为编辑模式
        originalData: null
    }
    tableData.value.push(newRecord)
    ElMessage.success('已添加新记录')
}

// 编辑行
const editRow = (row) => {
    // 备份原始数据，以便取消时恢复
    row.originalData = JSON.parse(JSON.stringify(row))

    // 清理占位文本
    if (row.periodWaterConsumption === '无数据，点击手动录入' || row.periodWaterConsumption === '点击录入') {
        row.periodWaterConsumption = ''
    }
    if (row.allocAmount === '点击录入') {
        row.allocAmount = ''
    }

    // 设置编辑状态
    row.isEditing = true
}

// 保存行
const saveRow = (row) => {
    // 验证必填字段
    const requiredFields = [
        { field: 'unitType', name: '单耗单位' },
        { field: 'area', name: '区域' },
        { field: 'periodUnit', name: '周期单位' },
        { field: 'period', name: '周期' },
        { field: 'periodWaterConsumption', name: '周期用水量' },
        { field: 'allocAmount', name: '分摊数量' },
    ]

    for (const item of requiredFields) {
        if (!row[item.field]) {
            ElMessage.warning(`请填写${item.name}`)
            return
        }
    }

    // 数值验证
    if (isNaN(Number(row.periodWaterConsumption))) {
        ElMessage.warning('周期用水量必须为数字')
        return
    }

    if (isNaN(Number(row.allocAmount))) {
        ElMessage.warning('分摊数量必须为数字')
        return
    }

    if (row.commonValue && isNaN(Number(row.commonValue))) {
        ElMessage.warning('通用值必须为数字')
        return
    }

    if (row.advancedValue && isNaN(Number(row.advancedValue))) {
        ElMessage.warning('先进值必须为数字')
        return
    }

    // 计算单耗值
    if (row.periodWaterConsumption && row.allocAmount &&
        !isNaN(parseFloat(row.periodWaterConsumption)) &&
        !isNaN(parseFloat(row.allocAmount)) &&
        parseFloat(row.allocAmount) > 0) {
        const consumption = parseFloat(row.periodWaterConsumption) / parseFloat(row.allocAmount)
        row.unitConsumption = consumption.toFixed(2)
    } else {
        row.unitConsumption = '自动生成'
    }

    // 退出编辑状态
    row.isEditing = false
    row.originalData = null
    // 这里可以添加保存到后端的逻辑
    ElMessage.success('保存成功')
}

// 取消编辑
const cancelEdit = (row) => {
    if (row.originalData) {
        // 如果是编辑现有记录，恢复原始数据
        Object.keys(row.originalData).forEach(key => {
            if (key !== 'originalData' && key !== 'isEditing') {
                row[key] = row.originalData[key]
            }
        })
        row.isEditing = false
        row.originalData = null
    } else {
        // 如果是新增记录，直接删除该行
        const index = tableData.value.indexOf(row)
        if (index !== -1) {
            tableData.value.splice(index, 1)
        }
    }
    ElMessage.info('已取消编辑')
}

// 删除行
const deleteRow = (row) => {
    ElMessageBox.confirm('确认删除此记录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        const index = tableData.value.indexOf(row)
        if (index !== -1) {
            tableData.value.splice(index, 1)
            ElMessage.success('删除成功')
        }
    }).catch(() => {
        // 取消删除
    })
}

// 删除单位
const deleteUnit = (unit) => {
    ElMessageBox.confirm(`确定要删除单位"${unit.symbol}"吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        const index = unitList.value.findIndex(item => item.id === unit.id)
        if (index !== -1) {
            unitList.value.splice(index, 1)
            ElMessage.success('删除成功')
        }
    }).catch(() => { })
}

// 获取周期选择器类型
const getPeriodPickerType = (periodUnit) => {
    switch (periodUnit) {
        case 'a': return 'year'
        case 'm': return 'month'
        case 'd': return 'date'
        case 's': return 'month'
        default: return 'year'
    }
}

// 获取周期选择器占位符
const getPeriodPlaceholder = (periodUnit) => {
    switch (periodUnit) {
        case 'a': return '请选择年份'
        case 'm': return '请选择月份'
        case 'd': return '请选择日期'
        case 's': return '请选择季度'
        default: return '请选择'
    }
}

// 获取周期选择器格式
const getPeriodFormat = (periodUnit) => {
    switch (periodUnit) {
        case 'a': return 'YYYY'
        case 'm': return 'YYYY-MM'
        case 'd': return 'YYYY-MM-DD'
        case 's': return 'YYYY-[Q]Q'
        default: return 'YYYY'
    }
}

// 获取周期选择器值格式
const getPeriodValueFormat = (periodUnit) => {
    switch (periodUnit) {
        case 'a': return 'YYYY'
        case 'm': return 'YYYY-MM'
        case 'd': return 'YYYY-MM-DD'
        case 's': return 'YYYY-[Q]Q'
        default: return 'YYYY'
    }
}

// 格式化周期显示
const formatPeriodDisplay = (period, periodUnit) => {
    if (!period) return '';

    // 对于已经格式化好的值，直接返回
    return period;
}

// 处理周期变更
const handlePeriodChange = (row) => {
    if (!row.period) return;

    // 检查是否与表格中其他行的周期重复（只检查同一表格内的数据）
    const isDuplicate = tableData.value.some(item =>
        item !== row &&
        item.tableId === row.tableId &&
        item.periodUnit === row.periodUnit &&
        item.period === row.period
    );

    if (isDuplicate) {
        ElMessage.warning('该周期已存在，请选择其他周期');
        row.period = '';
        return;
    }

    handleCellChange();
}

// 周期单位变更处理
const handlePeriodUnitChange = (row) => {
    // 周期单位变更时，清空已选择的周期值
    row.period = '';
    handleCellChange();
}

// 从单耗单位中提取水量单位
const extractWaterUnitFromUnitType = (unitType) => {
    if (!unitType) return 'm³';

    // 提取斜杠前的部分，如 m³/(人·a) 提取 m³
    let match = unitType.match(/^([^\/]+)\//);
    if (match && match[1]) {
        return match[1];
    }

    return 'm³'; // 默认水量单位
}

// 处理单耗单位变更
const handleUnitTypeChange = (row) => {
    // 从单耗单位中提取分摊单位
    row.allocUnit = extractAllocUnitFromUnitType(row.unitType);

    // 从单耗单位中提取水量单位
    row.waterUnit = extractWaterUnitFromUnitType(row.unitType);

    handleCellChange();
}

// 从单耗单位中提取分摊单位
const extractAllocUnitFromUnitType = (unitType) => {
    if (!unitType) return '';

    // 先尝试提取 / 后括号内的部分，如 m³/(人·a) 提取 人·a
    let match = unitType.match(/\/\((.*?)\)$/);
    if (match && match[1]) {
        return match[1];
    }

    // 如果没有括号，则尝试提取 / 后面的部分，如 m³/万粒 提取 万粒，或 m³/t 提取 t
    match = unitType.match(/\/([^\/\(\)]+)$/);
    if (match && match[1]) {
        return match[1];
    }

    return '';
}

// 视图切换
const currentView = ref('table')

// 为D3图表准备数据
const chartDataForD3 = computed(() => {
    return filteredTableData.value
        .filter(item =>
            item.unitConsumption &&
            item.unitConsumption !== '自动生成' &&
            !isNaN(parseFloat(item.unitConsumption))
        )
        .sort((a, b) => {
            // 按照周期排序
            return a.period.localeCompare(b.period)
        })
        .map(item => ({
            period: formatPeriodDisplay(item.period, item.periodUnit),
            unitType: item.unitType,
            area: item.area,
            unitConsumption: item.unitConsumption,
            commonValue: item.commonValue,
            advancedValue: item.advancedValue
        }));
});

function handleExport() {
    const $table = tableRef.value;
    if ($table) {
        $table.openExport();
    }
}
</script>

<style scoped>
.title-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    padding: 0 20px;
}


.unit-manage-btn {
    margin-left: auto;
}

.header-container {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    gap: 16px;
    margin-bottom: 16px;
    padding: 10px 0;
    border-bottom: 1px solid #eee;
}

.current-table {
    font-size: 16px;
    display: flex;
    align-items: center;
}

.el-dropdown-link {
    cursor: pointer;
    display: flex;
    align-items: center;
    color: #1aba8e;
    font-weight: bold;
    margin-left: 10px;
}

.header-actions {
    display: flex;
    gap: 10px;
}

.operation-buttons .el-button {
    margin-right: 5px;
}

.table-footer {
    margin-top: 20px;
    display: flex;
    justify-content: center;
}

.table-footer .el-button {
    background-color: #1aba8e;
    border-color: #1aba8e;
}

.empty-value {
    color: #999;
    cursor: pointer;
}

.empty-value:hover {
    color: #1aba8e;
}

.unit-manage-header {
    margin-bottom: 15px;
}

.unit-list-container {
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #ebeef5;
}

.unit-list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.unit-list-header h3 {
    margin: 0;
    font-size: 16px;
    color: #333;
}

.view-switch {
    margin-left: auto;
}

.chart-container {
    height: 500px;
    padding: 20px;
}

.chart {
    width: 100%;
    height: 100%;
}
</style>